﻿using System;
using System.Collections.Generic;
using Opalis.QuickIntegrationKit;
using Microsoft.Exchange.WebServices.Data;
using Microsoft.Exchange.WebServices.Autodiscover;
using System.Text;
using System.Net;
using System.IO;

namespace ExchangeMail
{
    [OpalisObject("Get Attachments")]
    public class GetAttachment : IOpalisObject
    {
        private MailboxSettings settings;
        private String exchangeVersion = String.Empty;
        private String emailID = String.Empty;
        private String SaveLocation = String.Empty;
        private String userName = String.Empty;
        private String password = String.Empty;
        private String domain = String.Empty;
        private String serviceURL = String.Empty;

        [OpalisConfiguration]
        public MailboxSettings Settings
        {
            get { return settings; }
            set { settings = value; }
        }


        public void Design(IOpalisDesigner designer)
        {
            designer.AddInput("Email ID");
            designer.AddInput("Save Location").WithFolderBrowser();
            designer.AddOutput("Attachments Saved").AsNumber();
            designer.AddCorellatedData(typeof(SavedAttachment));
        }

        public void Execute(IOpalisRequest request, IOpalisResponse response)
        {
            userName = settings.UserName;
            password = settings.Password;
            domain = settings.Domain;
            serviceURL = settings.ServiceUrl;
            exchangeVersion = settings.ExchangeVersion;

            emailID = request.Inputs["Email ID"].AsString();
            SaveLocation = request.Inputs["Save Location"].AsString();

            ExchangeService service = new ExchangeService();
            switch (exchangeVersion)
            {
                case "Exchange2007_SP1":
                    service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                    break;
                case "Exchange2010":
                    service = new ExchangeService(ExchangeVersion.Exchange2010);
                    break;
                case "Exchange2010_SP1":
                    service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
                    break;
                default:
                    service = new ExchangeService();
                    break;
            }

            service.Credentials = new WebCredentials(userName, password, domain);
            String AccountUrl = userName + "@" + domain;

            if (serviceURL.Equals("Autodiscover")) { service.AutodiscoverUrl(AccountUrl); }
            else { service.Url = new Uri(serviceURL); }

            EmailMessage message = EmailMessage.Bind(service, emailID);

            if (message.HasAttachments)
            {
                response.Publish("Attachments Saved", message.Attachments.Count);
                response.WithFiltering().PublishRange(getAttachments(message));
            }
            else
            {
                response.Publish("Attachments Saved", 0);
            }
        }
        private IEnumerable<SavedAttachment> getAttachments(EmailMessage message)
        {
            foreach(FileAttachment attach in message.Attachments)
            {
                attach.Load();
                FileStream fs = new FileStream(SaveLocation + "\\" + attach.Name.ToString(),FileMode.Create);
                fs.Write(attach.Content, 0, attach.Content.Length);
                fs.Close();
                fs.Dispose();
                yield return new SavedAttachment(attach.Name.ToString(), SaveLocation);
            }
        }
    }
}
